package br.com.pucrs.tcc.scheduler;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class EventoScheduler implements ServletContextListener {
	private Scheduler scheduler;

	protected void init() throws Exception {
		try {
			scheduler = new StdSchedulerFactory().getScheduler();

			JobDetail job1 = JobBuilder.newJob(EventoJob.class).withIdentity("job1", "group1").build();
			
			//Cria uma tarefa para rodar todos os dias as 00:30
			Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1").withSchedule(CronScheduleBuilder.cronSchedule("0 30 0 * * ?")).build();

			scheduler.scheduleJob(job1, trigger);
			scheduler.start();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		restart();
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		
		try {

			init();

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void restart() {
		try {
			scheduler.shutdown(true);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
